package com.huo.aspect;

import com.huo.common.enumtype.EnabledAndDisabledEnum;
import com.huo.task.dao.TaskLogMapper;
import com.huo.task.entity.TaskLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component  
@Aspect
public class TaskLogAOP {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private TaskLogMapper taskLogMapper;

	@Pointcut("execution (* *.*(..))&&@annotation(com.huo.annotation.TaskLogAnnotation)")
	public void log(){}

	@Before("log()")
	 public void doBefore(JoinPoint joinPoint){
		 try {
			 String classType = joinPoint.getTarget().getClass().getName();
			 Class<?> clazz = Class.forName(classType);
			 String clazzSimpleName = clazz.getName();
			 String methodName = joinPoint.getSignature().getName();
			 TaskLog taskManagerLog = new TaskLog();
			 taskManagerLog.setClassname(clazzSimpleName);
			 taskManagerLog.setMethodname(methodName);
			 taskManagerLog.setOperatetime(new Date());
			 taskManagerLog.setTasktype(Integer.valueOf(EnabledAndDisabledEnum.ENABLED.getCode()));
			 taskLogMapper.insert(taskManagerLog);
		 } catch (Exception e) {
			 logger.error(e.getMessage(),e);
		 }
	 }

	@After("log()")
	public void doAfter(JoinPoint joinPoint) {
		try {
			String classType = joinPoint.getTarget().getClass().getName();
			Class<?> clazz = Class.forName(classType);
			String clazzSimpleName = clazz.getName();
			String methodName = joinPoint.getSignature().getName();
			TaskLog taskManagerLog = new TaskLog();
			taskManagerLog.setClassname(clazzSimpleName);
			taskManagerLog.setMethodname(methodName);
			taskManagerLog.setOperatetime(new Date());
			taskManagerLog.setTasktype(Integer.valueOf(EnabledAndDisabledEnum.DISABLED.getCode()));
			taskLogMapper.insert(taskManagerLog);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}

	@AfterThrowing(throwing="ex",pointcut = "log()")
	public void throwss(JoinPoint joinPoint,Throwable ex) {
		try {
			logger.info(ex.getMessage());
			String classType = joinPoint.getTarget().getClass().getName();
			Class<?> clazz = Class.forName(classType);
			String clazzSimpleName = clazz.getName();
			String methodName = joinPoint.getSignature().getName();
			TaskLog taskManagerLog = new TaskLog();
			taskManagerLog.setClassname(clazzSimpleName);
			taskManagerLog.setMethodname(methodName);
			taskManagerLog.setOperatetime(new Date());
			taskManagerLog.setTasktype(Integer.valueOf(EnabledAndDisabledEnum.DISABLED.getCode()));
			taskManagerLog.setRemark(ex.getMessage());
			taskManagerLog.setDetailremark(ex.getMessage() + "  " + ex);
			taskLogMapper.insert(taskManagerLog);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
